import sys
import aggregator
import shlex

from backends.support import ResourceCategory, ResourceRawHTML
from cmd import Cmd

class PolyglotCmd(Cmd):
    def do_authenticate(self, args):
        """Authenticates with a backend. Args: backend, username, password, school"""
        args = shlex.split(args)

        if len(args) != 4:
            print("Wrong number of args")
            return

        name = args[0]
        self.backend = aggregator.load_backend(name)

        config = {
            "Email": args[1],
            "Username": args[1],
            "Password": args[2],
            "School": args[3]
        }

        if aggregator.authenticate(self.backend, config):
            print("OK")
        else:
            print("Authentication failed")
            return

        course_set = self.backend.courses

        self.courses = {}

        for course in course_set:
            print(course.title)
            self.courses[course.title] = course

    def dump_resource(self, rsrc, expand):
        if isinstance(rsrc, ResourceCategory):
            print(rsrc.name)

            if expand:
                for child in rsrc.children:
                    print("..." + child.name)

                for child in rsrc.contents:
                    print("")
                    self.dump_resource(child, False)

        elif isinstance(rsrc, ResourceRawHTML):
            print(rsrc.name + ": " + rsrc.html)
        else:
            print(rsrc.name + " (" + type(rsrc).__name__ + ")")

    def find_resource(self, root, path):
        if len(path) == 0:
            return root

        if isinstance(root, ResourceCategory):
            for child in root.children:
                if child.name == path[0]:
                    return self.find_resource(child, path[1:])

            print("Can't find " + path[0])
            return

        print("Wrong rsrc type with " + ",".join(path))

    def do_resources(self, args):
        args = shlex.split(args) 

        if len(args) == 0:
            print("Must specify course")
            return

        self.dump_resource(self.find_resource(self.courses[args[0]].resources, args[1:]), True)

    def do_grades(self, _):
        for course in self.backend.courses:
            try:
                print(course.title + ": " + str(course.grade_summary * 100) + "%")
            except AttributeError:
                print(course.title + ": (N/A)")

    def tasks(self, course):
        try:
            for task in course.tasks:
                print("- " + task.name)
        except AttributeError:
            print("(tasks N/A)")

    def do_tasks(self, args):
        if args:
            self.tasks(self.courses[shlex.split(args)[0]])
        else:
            for course in self.backend.courses:
                print(course.title + ":")
                self.tasks(course)
                print()

    def do_wget(self, url):
        """
        Download file using loaded backend's session.
        Useful for ./export-gdoc, etc.
        """

        u = self.backend.session.get(url)
        with open("download.bin", "wb") as f:
            f.write(u.content)

    def do_quit(self, _):
        """Quits polyglot"""
        sys.exit(0)

prompt = PolyglotCmd()
prompt.prompt = "> "
prompt.cmdloop()
